package com.chendx.store.comment.service.impl;

import com.chendx.model.common.dtos.ResponseResult;
import com.chendx.model.common.enums.AppHttpCodeEnum;
import com.chendx.model.goodsComment.dto.SkuCommentDto;
import com.chendx.model.goodsComment.pojo.SkuComment;
import com.chendx.model.goodsComment.vo.CommentCountVo;
import com.chendx.model.user.pojo.User;
import com.chendx.store.comment.feign.OrderFeign;
import com.chendx.store.comment.service.GoodsCommentService;
import com.chendx.store.common.entity.IdWorker;
import com.chendx.store.common.fastdfs.FastDFSClientUtil;
import com.chendx.store.utils.AppThreadLocalUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

/**
 * Created by chendx on 2022/4/19.
 */
@Service
public class GoodsCommentServiceImpl implements GoodsCommentService {

    @Autowired
    private IdWorker idWorker;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private OrderFeign orderFeign;
    @Autowired
    private FastDFSClientUtil client;

    @Value("${fdfs.url}")
    private String host;
    @Override
    public ResponseResult add(SkuCommentDto dto) {
        User user = AppThreadLocalUtils.get();
        if (user == null || user.getId() == null || user.getUsername() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        String username = user.getUsername();
        String userId = String.valueOf(user.getId());
        if (dto == null || dto.getSkuid() == null || dto.getSpuid() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        SkuComment skuComment = new SkuComment();
        skuComment.setC_id(idWorker.nextId()+"");
        BeanUtils.copyProperties(dto,skuComment);
        skuComment.setThumbup(0);
        skuComment.setOrderitemid(dto.getOrderItemId());
        skuComment.setPublishdate(new Date());
        skuComment.setUserid(userId);
        skuComment.setHeadpic(user.getHeadPic());
        skuComment.setUsername(username);
        if (StringUtils.isEmpty(skuComment.getParentid())) {
            skuComment.setParentid("0");
        }
        SkuComment comment = mongoTemplate.save(skuComment);
        orderFeign.updateOrderItemStatus(skuComment.getOrderitemid());
        ResponseResult responseResult = ResponseResult.okResult(comment);
        responseResult.setHost(host);
        return responseResult;
    }

    @Override
    public ResponseResult list(@RequestBody SkuCommentDto dto) {
        if (dto == null ) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        Query query = null;
        int size = 20;
        if (!StringUtils.isEmpty(dto.getSkuid())){
            query = Query.query(Criteria.where("skuid").is(dto.getSkuid()));
        }
        if (!StringUtils.isEmpty(dto.getSpuid())){
            query = Query.query(Criteria.where("spuid").is(dto.getSkuid()));
        }
        if (!StringUtils.isEmpty(dto.getParentid())){
            query = Query.query(Criteria.where("parentid").is(dto.getParentid()));
        }
        query.limit(size).with(Sort.by(Sort.Direction.DESC,"publishdate"));

        List<SkuComment> skuComments = mongoTemplate.find(query, SkuComment.class);

        ResponseResult responseResult = ResponseResult.okResult(skuComments);
        responseResult.setHost(host);
        return responseResult;
    }

    @Override
    public ResponseResult findBySkuid(String skuId) {
        if (StringUtils.isEmpty(skuId)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Query query = Query.query(Criteria.where("skuid").is(skuId));
        List<SkuComment> skuComments = mongoTemplate.find(query, SkuComment.class);
        ResponseResult responseResult = ResponseResult.okResult(skuComments);
        responseResult.setHost(host);
        return responseResult;
    }

    @Override
    public ResponseResult findBySpuid(String spuId) {
        if (StringUtils.isEmpty(spuId)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Query query = Query.query(Criteria.where("spuid").is(spuId));
        List<SkuComment> skuComments = mongoTemplate.find(query, SkuComment.class);
        ResponseResult responseResult = ResponseResult.okResult(skuComments);
        responseResult.setHost(host);
        return responseResult;
    }

    @Override
    public ResponseResult findByParentid(String parentId) {
        if (StringUtils.isEmpty(parentId)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Query query = Query.query(Criteria.where("parentid").is(parentId));
        List<SkuComment> skuComments = mongoTemplate.find(query, SkuComment.class);
        ResponseResult responseResult = ResponseResult.okResult(skuComments);
        responseResult.setHost(host);
        return responseResult;
}

    @Override
    public ResponseResult findCountBySkuid(String skuid) {
        if (StringUtils.isEmpty(skuid)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Query query = Query.query(Criteria.where("skuid").is(skuid));
        long count = mongoTemplate.count(query, SkuComment.class);
        return ResponseResult.okResult(count);
    }



    @Override
    public CommentCountVo loadCommentDetail(String skuid) {
        if (StringUtils.isEmpty(skuid)) {
            return null;
        }
        Query query = Query.query(Criteria.where("skuid").is(skuid).and("parentid").is("0"));
        List<SkuComment> skuComments = mongoTemplate.find(query, SkuComment.class);
        Long count = Long.valueOf(skuComments.size());
        long favorableCount = skuComments.stream().filter(skuComment -> skuComment.getStar() == 5).count();
        CommentCountVo commentVo = new CommentCountVo();
        Float favorable = Float.valueOf(0);
        if (favorableCount != 0){
            BigDecimal bigDecimal = new BigDecimal(favorableCount / count);
            bigDecimal = bigDecimal.setScale(2, RoundingMode.HALF_UP);
            favorable = bigDecimal.floatValue() * 100;
        }
        commentVo.setFavorable(favorable);
        commentVo.setCommentCount(count);

        return commentVo;
    }


    @Override
    public ResponseResult upload(MultipartFile imgFile) {
        User user = AppThreadLocalUtils.get();
        if (user == null || user.getId() == null || user.getUsername() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        try {
            String uploadFile = client.uploadFile(imgFile);

            ResponseResult responseResult = ResponseResult.okResult(uploadFile);
            responseResult.setHost(host);
            return responseResult;
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
    }

    @Override
    public ResponseResult handleRemove(String filePath) {
        if (StringUtils.isEmpty(filePath)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        client.delFile(filePath);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult handlesRemove(String filePaths) {
        if (StringUtils.isEmpty(filePaths)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (filePaths.lastIndexOf(",") != -1){
            filePaths = filePaths.substring(0,filePaths.length()-1);
        }
        String[] imageUrls = filePaths.split(",");
        for (String imageUrl : imageUrls){
            client.delFile(imageUrl);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
